package com.example.linktop.broadcastonedemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter;
    private  NetWorkChangeReceiver netWorkChangeReceiver; //网络状况监视器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"); //注册系统网络状况通知
        netWorkChangeReceiver = new NetWorkChangeReceiver();
        registerReceiver(netWorkChangeReceiver, intentFilter);


    }


    class NetWorkChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
//            Toast.makeText(getApplicationContext(),"network change", Toast.LENGTH_SHORT).show();
            //获取网络
            ConnectivityManager netManger = (ConnectivityManager)getSystemService(context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = netManger.getActiveNetworkInfo();

            String mesg;
            if (netInfo != null && netInfo.isAvailable()) {

                mesg = "net available";
            } else  {
                mesg = "net unavailable";

            }

            Toast.makeText(context, mesg, Toast.LENGTH_SHORT).show();



        }
    }


    @Override
    protected void onDestroy() {

        unregisterReceiver(netWorkChangeReceiver);

        super.onDestroy();
    }
}
